package com.tc.property.util;


import com.tc.property.config.model.ConfigContext;
import com.tc.property.config.model.ConfigItem;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;

public class Utils {

	/**
	 * 环境变量和系统变量
	 */
	private static Properties sysProps = new Properties();

	public static Properties getSysProps() {
		// if (sysProps.size() == 0) {
		sysProps.putAll(System.getenv());
		sysProps.putAll(System.getProperties());
		// }
		return sysProps;
	}
	

	public static String resolveSystemProperty(String key) {
		try {
			String value = System.getProperty(key);
			if (value == null) {
				value = System.getenv(key);
			}
			if (value == null) {
				value = "";
			}
			return value;
		} catch (Throwable ex) {
			return "";
		}
	}

	public static Properties getPropsFromContext(ConfigContext configContext) {
		Properties props = new Properties();
		Set<Entry<String, ConfigItem>> entrySet = configContext.getContextItemMap().entrySet();
		for (Entry<String, ConfigItem> entry : entrySet) {
			if (entry.getValue() != null && entry.getValue().getValue() != null) {
				props.put(entry.getKey(), entry.getValue().getValue());
			}
		}

		return props;
	}

	public static String getLocalHostName() {
		try {
			return InetAddress.getLocalHost().getHostName();
		} catch (UnknownHostException ignore) {
		}
		return null;
	}

}
